package yxk.utils;

import com.alibaba.fastjson.JSONObject;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;

import javax.net.ssl.*;
import java.io.*;
import java.net.*;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import kd.hr.hbp.common.util.HRStringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

public class HttpRequestUtil {
    private static Log log = LogFactory.getLog(HttpRequestUtil.class);
    private static final int MAX_RETRY = 3;
    public static String getPostResult(String sendUrl,Map<String,String> header,String param, String contentType) throws Exception {
        if (sendUrl.startsWith("https")) {
            return getResultByHttps(sendUrl,header, param,contentType);
        }
        return getResultByHttp(sendUrl, header,param, contentType);
    }



    public static String getResultByHttps(String urlPath,Map<String,String> header, String Json,String contentType) {

        String result = "";
        BufferedReader reader = null;
        HttpURLConnection conn = null;
        OutputStream out=null;
        try {
            ignoreHttpsCertificateVerified();
            URL url = new URL(urlPath);
            conn = (HttpURLConnection) url.openConnection();
            //conn.setHostnameVerifier(DO_NOT_VERIFY);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Content-Type", contentType);
            conn.setConnectTimeout(150000);
            conn.setReadTimeout(150000);
            if(header != null){
                for (String key : header.keySet()) {
                    conn.setRequestProperty(key,header.get(key));
                }
            }
            conn.setRequestProperty("accept","*/*");
            log.info("getResultByHttps.getResponseCode:{}",conn);
            int retries = 5;
            while (retries > 0) {
                try {
                    out = conn.getOutputStream();
                    out.write(Json.getBytes());
                    log.info("getResultByHttps.getResponseCode:{}",conn.getResponseCode());
                    if (conn.getResponseCode() == 200) {
                        reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
                        result = reader.readLine();
                    }
                    break;
                } catch (SocketException so) {
                    log.error("连接失败，正在重试...");
                    log.error("getResultByHttps.so:{}",so);
                    retries--;
                    try {
                        Thread.sleep(1000); // 等待1秒后重试
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
            }

        }
        catch(IOException io){
            log.error("HTTPS请求IO流出现错误：{}",io);
            io.printStackTrace();
            log.error("HTTPS请求IO流出现错误getMessage()：{}",io.getMessage());
        }
        catch (Exception e) {
            log.error("HTTPS请求发送失败：{}",e);
            e.printStackTrace();
            log.error("HTTPS请求发送失败getMessage：{}",e.getMessage());
        }
        finally {
            try {
                if (reader != null) {
                    reader.close();
                }
                if(out != null){
                    out.close();
                }
                if(conn != null){
                    conn.disconnect();
                }
            } catch (IOException e) {
                log.info("请求流关闭失败：[{}]",e);
                e.printStackTrace();
            }

        }
        return result;
    }

    final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier()
    {
        public boolean verify(String arg0, SSLSession arg1) {
            return true;
        }
    };
/*
    public static void trustAllHosts() {
        TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager()
        {

            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[] {};
            }

            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

            }

            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

            }
        }

        };

        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        }
        catch (Exception e) {
            e.printStackTrace();
        }

    }*/




    private static String getResultByHttp(String sendUrl,Map<String,String> header, String param, String contentType)
            throws IOException {

        HttpURLConnection conn = null;
        OutputStream out = null;
        BufferedReader reader = null;
        InputStream input=null;
        String result = "";
        try {

            URL url = new URL(sendUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", contentType);
            if(header != null){
                for (String key : header.keySet()) {
                    conn.setRequestProperty(key, header.get(key));
                }
            }
            conn.setConnectTimeout(15000);
            conn.setReadTimeout(150000);
            conn.connect();
            out = conn.getOutputStream();
            out.write(param.getBytes());
            out.flush();
            out.close();
            input = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
            String line;
            StringBuffer sb = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            result = sb.toString();
        } catch (IOException io) {
            log.info("HTTP请求io流失败：{}",io);
            log.info("HTTP请求io流失败getMessage：{}",io.getMessage());
            io.printStackTrace();
        }catch (Exception e) {
            log.info("HTTP请求发送失败：{}",e);
            log.info("HTTP请求发送失败getMessage：{}",e.getMessage());
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (reader != null) {
                reader.close();
            }
            if(out != null){
                out.close();
            }
            if(conn != null){
                conn.disconnect();
            }
            if(input != null){
                input.close();
            }
        }

        return result;
    }

    /**
     * <p>Description: get方式请求接口
     * @param url            请求路径
     * @param headParams    http头参数
     */
    public static String sendJsonGet(String url, String path,Map<String, String> headParams) {
        String result = "";
        BufferedReader in = null;
        try {
            // 拼接参数,可以用URIBuilder,也可以直接拼接在?传值，拼在url后面
            //URIBuilder uriBuilder = new URIBuilder(url);
            String psthUrl=URLEncoder.encode(path,"utf-8");

            URL realUrl =new URL(url+"?"+psthUrl);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 获取请求头Map
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 设置通用的请求属性\
            connection.setRequestProperty("Content-type", "application/json; charset=UTF-8");
            for (String key : headParams.keySet()) {
                connection.setRequestProperty(key,headParams.get(key));
            }
            connection.setConnectTimeout(180000);
            connection.setReadTimeout(180000);
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            System.out.println("请求地址  =="+url);
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            log.error("发送GET请求出现异常！\r\n" + e);
            result = e.toString();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                log.error(e2);
            }
        }
        return result;
    }


    public static String getPutResult(String url, Map<String, String> headParams,String requestBody ,String conType) throws IOException {
        BufferedReader reader=null;
        OutputStream out=null;
        HttpURLConnection con=null;
        String result="";
        try {
            URL realUrl = new URL(url);
            con = (HttpURLConnection) realUrl.openConnection();
            con.setRequestMethod("PUT");

            // 设置请求头
            con.setRequestProperty("Content-Type",conType);
            con.setRequestProperty("User-Agent", "Mozilla/5.0");
            if(headParams != null && headParams.size()>0) {
                for (String key : headParams.keySet()) {
                    con.setRequestProperty(key, headParams.get(key));
                }
            }
            // 设置请求体
            con.setDoOutput(true);
            out = con.getOutputStream();
            out.write(requestBody.getBytes("UTF-8"));
            // 发送请求并获取响应
            int responseCode = con.getResponseCode();
            reader= new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = reader.readLine()) != null) {
                response.append(inputLine);
            }
            result = response.toString();
        } catch (Exception e) {
            log.info("Exception Occurred : {}",e.getMessage());
        } finally {
            if (reader != null) {
                reader.close();
            }
            out.close();
            con.disconnect();
        }
        return result;
    }

    public static String testPost(String url, Map<String,String> header, JSONObject body, String contentType) throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {

        // 创建HttpClient对象
        CloseableHttpClient httpClient = createHttpClient();

        // 创建HttpPost对象
        HttpPost httpPost = new HttpPost(url);

        // 设置请求头信息
        httpPost.setHeader("Content-Type", contentType);
        if (header != null && header.size() > 0) {
            for (String key : header.keySet()) {
                httpPost.setHeader(key,header.get(key));
            }
        }
        // 设置请求参数
        if (body != null && body.size() > 0) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (String key : body.keySet()) {
                params.add(new BasicNameValuePair(key, body.get(key).toString()));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        }

        // 发送POST请求
        HttpResponse httpResponse = httpClient.execute(httpPost);
        // 处理响应结果
        HttpEntity httpEntity = httpResponse.getEntity();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpEntity.getContent()));
        String line = null;
        StringBuffer sb=new StringBuffer();
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    }

    /**
     * 创建HttpClient对象
     */
    private static CloseableHttpClient createHttpClient() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        } }, null);
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
        return HttpClients.custom().setSSLSocketFactory(sslsf).build();
    }

    private static void ignoreHttpsCertificateVerified() {
        try {
            X509TrustManager trustManager = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }

                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            };
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[]{trustManager}, null);
            HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier((hostName, sslSession) -> !HRStringUtils.isEmpty(hostName));
        } catch (Exception exception) {
            log.error("ignoreHttpsCertificateVerified error", exception);
        }
    }
}
